const fs = require('fs');
const path = require('path');
const db = require('../config/database');

async function importFonts(jsonData) {
  for (const font of jsonData.data) {
    const { name, type, file, img } = font.attributes;
    const fontUrl = file?.data?.attributes?.url || '';
    const previewText = img?.data?.attributes?.url || '';
    try {
      await db.execute(
        `INSERT INTO fonts (name, font_family, font_url, preview_text, type) VALUES (?, ?, ?, ?, ?)`,
        [name, name, fontUrl, previewText, type]
      );
      console.log(`已导入字体: ${name}`);
    } catch (error) {
      if (error.code === 'ER_DUP_ENTRY') {
        console.log(`字体已存在，跳过: ${name}`);
      } else {
        throw error;
      }
    }
  }
}

async function importTemplateTypes(jsonData) {
  for (const type of jsonData.data) {
    const { name } = type.attributes;
    try {
      await db.execute(
        `INSERT INTO template_types (id, name) VALUES (?, ?) ON DUPLICATE KEY UPDATE name=VALUES(name)`,
        [type.id, name]
      );
      console.log(`已导入模板类型: ${name}`);
    } catch (error) {
      if (error.code === 'ER_DUP_ENTRY') {
        console.log(`模板类型已存在，跳过: ${name}`);
      } else {
        throw error;
      }
    }
  }
}

async function importTemplates(jsonData) {
  for (const tpl of jsonData.data) {
    const { name, templ_type, preview, thumbnail, width, height, json, tags, download_count } = tpl.attributes;
    try {
      await db.execute(
        `INSERT INTO templates (id, name, type_id, preview, thumbnail, width, height, json_data, tags, download_count, is_public) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE) ON DUPLICATE KEY UPDATE name=VALUES(name)`,
        [tpl.id, name, templ_type?.data?.id || null, preview, thumbnail, width, height, JSON.stringify(json), JSON.stringify(tags), download_count || 0]
      );
      console.log(`已导入模板: ${name}`);
    } catch (error) {
      if (error.code === 'ER_DUP_ENTRY') {
        console.log(`模板已存在，跳过: ${name}`);
      } else {
        throw error;
      }
    }
  }
}

async function main() {
  try {
    const data = fs.readFileSync(path.join(__dirname, '../../../shuju.md'), 'utf8');
    const blocks = [...data.matchAll(/```[\s\n]*({[\s\S]*?})\s*```/g)];
    let fontJson = null, typeJson = null, tplJsons = [];
    for (const block of blocks) {
      try {
        const obj = JSON.parse(block[1]);
        // 字体
        if (obj.data && Array.isArray(obj.data) && obj.data[0]?.attributes?.file) fontJson = obj;
        // 模板类型
        if (obj.data && Array.isArray(obj.data) && obj.data[0]?.attributes?.name && !obj.data[0]?.attributes?.file && !obj.data[0]?.attributes?.preview) typeJson = obj;
        // 模板
        if (obj.data && Array.isArray(obj.data) && obj.data[0]?.attributes?.preview) tplJsons.push(obj);
      } catch (e) { }
    }
    if (fontJson) {
      console.log('开始导入字体数据...');
      await importFonts(fontJson);
    }
    if (typeJson) {
      console.log('开始导入模板类型数据...');
      await importTemplateTypes(typeJson);
    }
    for (const tplJson of tplJsons) {
      console.log('开始导入模板数据...');
      await importTemplates(tplJson);
    }
    console.log('所有数据导入完成');
  } catch (error) {
    console.error('导入数据失败:', error);
    process.exit(1);
  }
}

main(); 